/*
 * @lc app=leetcode.cn id=92 lang=javascript
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
/**
 * 1. 找到预反转的节点的前一个节点
 * 2. 反转需要反转的部分
 * 3. 拼接链表
 */
var reverseBetween = function(head, left, right) {
    if (!head || !head.next) return head;
    const ret = new ListNode(null, head);
    // 查找反转的前一个节点
    let n = right - left + 1
    let cur = ret;
    
    while(--left){
        cur = cur.next
    }
    let temp = reverse(cur.next,n)

    cur.next = temp
    return ret.next
};

function reverse(head,n){
    if (!head || !head.next) return head;
    let p = null, cur = head;
    while(head && n-- > 0){
        let temp = cur.next
        cur.next = p
        p = cur
        cur = temp
    }

    head.next = cur
    return p
}

// @lc code=end

